package routers

/*
 * @Desc: 路由层
 * @author: bsyz
 * @version: v1.0.0
 */

import (
	"github.com/PhlexTheCharr/GoFurry-framework/common"
	"github.com/PhlexTheCharr/GoFurry-framework/docs"
	"github.com/PhlexTheCharr/GoFurry-framework/middleware"
	"github.com/PhlexTheCharr/GoFurry-framework/roof/env"
	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"sync"
)

var Router *router

type router struct{}

func NewRouter() *router {
	return &router{}
}

func init() {
	Router = NewRouter()
}

var once = sync.Once{}

func (router *router) Init() *gin.Engine {
	once.Do(func() {
	})
	// 启动 web
	r := gin.New()
	gin.SetMode(env.GetServerConfig().Server.Mode)
	if gin.IsDebugging() {
		pprof.Register(r, "/debug/pprof")
	}
	_ = r.SetTrustedProxies([]string{"127.0.0.1"})
	// 中间件
	r.Use(middleware.TlsHandler())
	r.Use(middleware.Recover())         // 捕获恐慌
	r.Use(middleware.CrossMiddleware()) // 跨域
	if env.GetServerConfig().Waf.WafSwitch == 1 {
		r.Use(middleware.CorazaMiddleware(r)) // CorazaWAF
	}

	r.NoRoute(findNoRoute)
	r.NoMethod(findNoMethod)
	docs.SwaggerInfo.BasePath = ""
	if gin.IsDebugging() {
		r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	}

	userApi(r.Group("/api/system/user"))

	return r
}

func findNoRoute(ctx *gin.Context) {
	common.NewResponse(ctx).Error("链接不存在")
}

func findNoMethod(ctx *gin.Context) {
	common.NewResponse(ctx).Error("方法不存在")
}
